<template>
  <div class="compact-container">
    <!-- Compact search row with Add button on the right -->
    <div class="search-row">
      <span class="search-label">供应商名称：</span>
      <el-input v-model="Vendor_name" size="small" class="search-input" />
      <span class="search-label">退货单编号：</span>
      <el-input v-model="Purret_code" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加退货单</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table 
        :data="flattenedData" 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }"
        :row-style="{ height: '36px' }"
        :span-method="objectSpanMethod"
        v-loading="loading"
      >
        <!-- Table columns -->
        <el-table-column fixed width="180px" prop="purret_code" label="退货单编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row)">{{ scope.row.purret_code }}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="pu_audit" label="是否审核" width="100px">
          <template #default="{row}">
            {{row.pu_audit === '1' ? '已审核' : row.pu_audit === '2' ? '驳回' : '未审核'}}
          </template>
        </el-table-column>

        <el-table-column prop="po_code" label="关联采购单号" width="180px" />
        <el-table-column prop="vendor_name" label="供应商" width="180px" />
        <el-table-column prop="purret_returntime" label="退货时间" width="180px">
          <template #default="{row}">{{ formatDate(row.purret_returntime) }}</template>
        </el-table-column>
        <el-table-column prop="purret_returncause" label="退货原因" width="200px" />
        
        <!-- Detail columns -->
        <el-table-column prop="pro_name" width="150px" label="产品名称" />
        <el-table-column prop="pro_code" width="180px" label="产品编号" />
        <el-table-column prop="pro_brand" width="120px" label="品牌" />
        <el-table-column prop="pro_model" width="150px" label="规格型号" />
        <el-table-column prop="podet_retqty" width="120px" label="待退货数量" align="right" />
        <el-table-column prop="number_returns" width="120px" label="退货数量" align="right" />
        <el-table-column prop="sun" width="120px" label="退货总计" align="right" />
        <el-table-column prop="create_by" label="创建人" width="120px" />
        <el-table-column prop="create_time" label="创建时间" width="180px">
          <template #default="{row}">{{ formatDate(row.create_time) }}</template>
        </el-table-column>
        
        <!-- Action column -->
        <el-table-column fixed="right" prop="caozuo" label="操作" width="220px">
          <template #default="scope">
            <div class="action-group">
              <el-button 
                size="small" 
                @click="handleEdit(scope.row)" 
                :disabled="scope.row.pu_audit === '1' || scope.row.pu_audit === '2'"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handAudit(scope.row)"
                :disabled="scope.row.pu_audit === '1' || scope.row.pu_audit === '2'"
              >
                审核
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.pu_audit === '1' || scope.row.pu_audit === '2'"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 审核对话框 -->
  <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
    <template #header>
      <div style="text-align: left; font-size: 16px; font-weight: bold;">
        审核
      </div>
    </template>
    <hr>
    <div style="text-align: left;padding: 10px 0px;">
      <p>审核结果</p>
      <div class="my-2 ml-4">
        <el-radio-group v-model="auditStatus">
          <el-radio value="1">通过</el-radio>
          <el-radio value="2">驳回</el-radio>
        </el-radio-group>
      </div>
      <div>
        <p>审核意见</p>
        <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
          :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
      </div>
    </div>
    <hr>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="updateAudit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import { ref, onMounted, markRaw } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    const datamax = store.state.PO_UpdeteArray

    const Router = useRouter();
    const tableData = ref([]);
    const flattenedData = ref([]);
    const spanArr = ref([]);
    const Purret_code = ref('');
    const Vendor_name = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const pageCount = ref(0);
    const loading = ref(false);
    
    // 审核相关状态
    const centerDialogVisible = ref(false);
    const auditStatus = ref('1');
    const auditOpinion = ref('');
    const currentRow = ref(null);

    // const getAuditText = (audit) => {
    //   return audit === '1' ? '已通过' : 
    //          audit === '2' ? '已驳回' : 
    //          '未审核';
    // };
     onMounted(() => {
      fill();
      count();
    });

    const processData = (data) => {
      const flatData = [];
      spanArr.value = [];
      let sun = 0;

      data.forEach(order => {
        const mainOrder = {
          ...order,
          pro_name: '',
          pro_code: '',
          pro_brand: '',
          pro_model: '',
          podet_inbound_quantity: '',
          podet_notstocked: '',
          number_returns: ''
        };

        const rowCount = order.details ? order.details.length : 1;
        spanArr.value.push(rowCount);

        if (order.details && order.details.length > 0) {
          order.details.forEach(detail => {
            flatData.push({ ...mainOrder, ...detail });
            if (detail.podet_retqty) {
              sun += (detail.podet_retqty + detail.number_returns);
            }
          });
        } else {
          flatData.push(mainOrder);
        }
      });

      flatData.forEach(item => {
        item.sun = sun;
      });

      return flatData;
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    }

    const fill = () => {
      loading.value = true;
      axios.get("http://localhost:5181/api/Pu/GetPuFyWhereSelect", {
        params: {
          Vendor_name: Vendor_name.value,
          Purret_code: Purret_code.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        const formattedData = res.data.map(item => ({
          ...item,
          purret_returntime: formatDate(item.purret_returntime),
          create_time: formatDate(item.create_time),
          update_time: formatDate(item.update_time)
        }));
        
        tableData.value = formattedData;
        flattenedData.value = processData(formattedData);
      }).catch((err) => {
        console.error('数据加载失败', err);
        ElMessage.error('数据加载失败');
      }).finally(() => {
        loading.value = false;
      });
    }

    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      const mergeColumns = [
        'purret_code', 'po_code', 'vendor_name', 'purret_returntime', 
        'purret_returncause', 'remark', 'create_by', 'create_time', 
        'update_by', 'update_time', 'warehouse_code', 'operation', 'pu_state',
        'pu_audit', 'sun','caozuo'
      ];
      
      if (mergeColumns.includes(column.property)) {
        let position = 0;
        for (let i = 0; i < spanArr.value.length; i++) {
          const count = spanArr.value[i];
          if (rowIndex < position + count) {
            return {
              rowspan: rowIndex === position ? count : 0,
              colspan: 1
            };
          }
          position += count;
        }
      }
    }

    const count = () => {
      axios.get("http://localhost:5181/api/Pu/GetPuWhereCount", {
        params: {
          Purret_code: Purret_code.value,
          Vendor_name: Vendor_name.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        pageCount.value = res.data;
      }).catch((err) => {
        console.error('总条数加载失败', err);
        ElMessage.error('总条数加载失败');
      });
    }

    const query = () => {
      currentPage.value = 1;
      fill();
      count();
    }

    function infoPage(row) {
      store.commit('PO_UpdeteArray', row)
      Router.push({
        path: '/main/Pinv/Puinfo',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    const reset = () => {
      Purret_code.value = '';
      Vendor_name.value = '';
      query();
    }

    const addEdit = () => {
      Router.push({ path: '/main/Pinv/PuAdd' });
    }

    const handleEdit = (row) => {
      store.commit('PO_UpdeteArray', row)
      Router.push({
        path: '/main/Pinv/PuUpdate',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    // 审核按钮点击事件
    function handAudit(row) {
      if (row.pu_audit === '0' || row.pu_audit === null) {
        currentRow.value = row;
        centerDialogVisible.value = true;
      } else {
        ElMessage.warning('该退货单已被审核，不可再次审核！');
      }
    }

    // 审核确认
    async function updateAudit() {
      try {
        // 构建审核请求数据
        const requestData = {
          pu_Order_Dto: {
            purret_id: currentRow.value.purret_id,
            po_id: currentRow.value.po_id,
            purret_code: currentRow.value.purret_code,
            pu_audit: auditStatus.value,
            pu_audit_by: localStorage.getItem('userLName'),
            pu_audit_time: new Date().toISOString(),
            pu_audit_remark: auditOpinion.value,
            warehouse_code: currentRow.value.warehouse_code,
          },
          pu_Details_Audit_Dtos: []
        };

        // 如果有明细数据，添加到请求中
        if (currentRow.value.details && currentRow.value.details.length > 0) {
          requestData.pu_Details_Audit_Dtos = currentRow.value.details.map(item => ({
            podet_id: item.podet_id,
            purret_id: item.purret_id,
            po_code: item.po_code,
            pro_name: item.pro_name,
            pro_code: item.pro_code,
            pro_brand: item.pro_brand,
            pro_model: item.pro_model,
            unitmeas_id: item.unitmeas_id,
            po_number: item.po_number,
            podet_inbound_quantity: item.podet_inbound_quantity,
            podet_notstocked: item.podet_notstocked,
            podet_retqty: item.podet_retqty,
            number_returns: item.number_returns
          }));
        }

        // 发送审核请求
        const result = await axios.put("http://localhost:5181/api/Pu/PutPuAudit", requestData, {
          headers: { 
            authorization: `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        });

        if (result.data === 1) {
          ElMessage.success('审核成功');
          centerDialogVisible.value = false;
          fill(); // 刷新数据
        } else if (result.data === 5) {
          ElMessage.error('已入库商品库存数量异常');
          centerDialogVisible.value = false;
        } else {
          ElMessage.error('审核失败');
        }
      } catch (error) {
        console.error('审核失败:', error);
        ElMessage.error(`审核失败: ${error.message}`);
      }
    }

    function handleDelete(row) {
      ElMessageBox.confirm(
        '此操作将删除该退货单信息，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
      .then(() => {
        return axios.put('http://localhost:5181/api/Pu/PutPuDelete', {
          purret_id: row.purret_id,
          del_flag: "1"
        }, {
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
      })
      .then((result) => {
        if (result.data>0) {
          ElMessage.success("删除成功");
          fill();
          count();
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch((error) => {
        console.error("删除失败:", error);
      });
    }

    const handleSizeChange = (val) => {
      pageSize.value = val;
      fill();
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fill();
    }

    // 关闭审核对话框
    function close() {
      centerDialogVisible.value = false;
      auditStatus.value = '1';
      auditOpinion.value = '';
    }

    return {
      tableData,
      flattenedData,
      Purret_code,
      Vendor_name,
      currentPage,
      pageSize,
      pageCount,
      loading,
      centerDialogVisible,
      auditStatus,
      auditOpinion,
      query,
      reset,
      addEdit,
      handleEdit,
      handleDelete,
      handAudit,
      updateAudit,
      handleSizeChange,
      handleCurrentChange,
      objectSpanMethod,
      formatDate,
      infoPage,
      // getAuditText,
      close
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
  margin-top: -10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}
</style>